// pages/editCardInfo/index.js
var app = getApp()
var regionDatas;
var pid;
var cid;
var aid;
var phoneNumber;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    image: '',
    hidenBut: true,
    provinces: [],
    province: "",
    citys: [],
    city: "",
    countys: [],
    county: '',
    value: [0, 0, 0],
    values: [0, 0, 0],
    condition: true,
    userCardInfo: {},
  },
  bindChange: function(e) {
    console.log(e);
    var val = e.detail.value
    var t = this.data.values;

    if (val[0] != t[0]) {
      var citys = [];
      var countys = [];
      var province = '';
      var city = '';
      var county = '';
      pid = this.data.provinces[val[0]].id;
      province = this.data.provinces[val[0]].name;
      if (regionDatas[val[0]].son && regionDatas[val[0]].son.length) {
        for (let i = 0; i < regionDatas[val[0]].son.length; i++) {
          citys.push(regionDatas[val[0]].son[i])
        }
        city = regionDatas[val[0]].son[0].name;
        cid = regionDatas[val[0]].son[0].id;
        if (regionDatas[val[0]].son[0] && regionDatas[val[0]].son[0].son.length) {
          for (let i = 0; i < regionDatas[val[0]].son[0].son.length; i++) {
            countys.push(regionDatas[val[0]].son[0].son[i])
          }
          county = regionDatas[val[0]].son[0].son[0].name;
          aid = regionDatas[val[0]].son[0].son[0].id;
        } else {
          countys = [];
          aid = '';
        }

      } else {
        city = '';
        citys = [];
        cid = '';
      }
      console.log('操作省/省Id：' + pid + '市ID：' + cid + '县区Id：' + aid)
      this.setData({
        province: province,
        city: city,
        citys: citys,
        county: county,
        countys: countys,
        values: val,
        value: [val[0], 0, 0]
      })


      return;
    }
    if (val[1] != t[1]) {
      var countys = [];
      var county = '';
      var city = '';
      cid = this.data.citys[val[1]].id;
      city = this.data.citys[val[1]].name;
      if (regionDatas[val[0]].son[val[1]].son && regionDatas[val[0]].son[val[1]].son.length) {
        for (let i = 0; i < regionDatas[val[0]].son[val[1]].son.length; i++) {
          countys.push(regionDatas[val[0]].son[val[1]].son[i])
        }
        aid = regionDatas[val[0]].son[0].son[0].id;
        county = regionDatas[val[0]].son[val[1]].son[0].name;
      } else {
        aid = '';
        county = '';
      }
      console.log('操作市/省Id：' + pid + '市ID：' + cid + '县区Id：' + aid)
      this.setData({
        city: city,
        county: county,
        countys: countys,
        values: val,
        value: [val[0], val[1], 0]
      })
      return;
    }
    if (val[2] != t[2]) {
      aid = this.data.countys[val[2]].id,
        console.log('操作县/省Id：' + pid + '市ID：' + cid + '县区Id：' + aid)
      this.setData({
        county: this.data.countys[val[2]].name,
        values: val
      })
      return;
    }
  },
  open: function() {
    var that = this;
    console.log('省：' + pid + '市：' + cid, '县：' + aid)
    that.setData({
      condition: !this.data.condition,
    })
  },
  //确认
  confirm: function(e) {
    var that = this;
    var data = that.data;
    var t = data.userCardInfo;
    var address = data.province + data.city + data.county;
    console.log('省：' + pid + '市：' + cid, '县：' + aid)
    t['Province'] = pid;
    t['City'] = cid;
    t['County'] = aid;
    t['address'] = address;
    console.log('确认地址', address)
    that.setData({
      condition: !data.condition,
      userCardInfo: t
    })
  },
  //取消  
  cancel: function() {
    pid = '',
      cid = '',
      aid = '',
      this.setData({
        condition: !this.data.condition
      })
  },
  //获取联动数据
  getRegionList: function() {
    var that = this;
    var data = [];
    var url = 'We_Miscellaneous/getRegionList';
    var calkdata = app.netWorkRequest(that, data, url, 'regionDatas')
  },
  //初始化联动数据
  initRegionData: function(data) {
    var that = this;
    regionDatas = data;
    var provinces = [];
    var citys = [];
    var countys = [];
    console.log('baby', data[0]);
    for (let i = 0; i < data.length; i++) {
      provinces.push(data[i]);
    }
    console.log('省份完成', provinces);
    for (let i = 0; i < data[0].son.length; i++) {
      citys.push(data[0].son[i])
    }
    console.log('city完成', citys);
    for (let i = 0; i < data[0].son[0].son.length; i++) {
      countys.push(data[0].son[0].son[i])
    }
    pid = provinces[0].id,
      cid = data[0].son[0].id,
      aid = data[0].son[0].son[0].id,
      that.setData({
        'provinces': provinces,
        'citys': citys,
        'countys': countys,
        'province': data[0].name,
        'city': data[0].son[0].name,
        'county': data[0].son[0].son[0].name
      })
    console.log('初始化完成');
  },
  getUserCardInfo: function() {
    var that = this;
    var data = [];
    var url = 'We_Community/getBrowsePersonalUserInfo'
    var calkdata = app.netWorkRequest(that, data, url, 'userCardInfo')
  },
  //写入缓存
  inputWriteCache: function(e) {
    var id = e.currentTarget.id;
    var val = e.detail.value;
    var that = this;
    var t = that.data.userCardInfo;
    console.log('id:' + id + '内容：' + val)
    t[id] = val;
    console.log('新数组', t)
    that.setData({
      userCardInfo: t,
    })
  },
  choicePortrait: function(count = 1) {
    var that = this;
    var data = that.data;
    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        //获取第一张图片地址 
        var filep = res.tempFilePaths[0];
        console.log('上传图片' + filep)
        var t = data.userCardInfo;
        // app.uploadImage(that, filep);
        // that.setData({
        //   hidenBut: !data.hidenBut,
        //   image: filep
        // })
        wx.redirectTo({
          url: '../shera/index?src=' + filep
        })
      }
    })
  },
  confirmImg: function() {
    var that = this;
    var data = that.data.image;
    var t = data.userCardInfo;
    app.uploadImage(that, data);
    that.setData({
      hidenBut: !data.hidenBut,
    })
  },
  updateHeadport: function(data) {
    console.log('头像',data)
    var that = this;
    var t = that.data.userCardInfo;
    t['Card_portrait'] = data;
    that.setData({
      userCardInfo: t
    })
  },
  //获取手机号码
  getPhoneNumber: function(e) {
    console.log(e)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
    var iv = e.detail.iv;
    var encryptedData = e.detail.encryptedData;
    if (!iv || iv == undefined || iv == 'undefined' || !encryptedData || encryptedData == undefined || encryptedData == 'undefined')
     return app.prompt('获取失败');
    var that = this;
    var data = [];
    data['iv'] = iv;
    data['encryptedData'] = encryptedData;
    var url = 'We_Businesscard/getUserWxBindingPhone'
    //data.splice('address', 1)
    console.log('iv：' + e.detail.iv, 'encryptedData：' + e.detail.encryptedData)
    wx.checkSession({
      success(e) {
        // session_key 未过期，并且在本生命周期一直有效
        console.log('session_key 未过期，并且在本生命周期一直有效：' + app.globalData.ss_key)
        data['ss_key'] = app.globalData.ss_key;
        var calkdata = app.netWorkRequest(that, data, url, 'phoneNumber')
      },
      fail(e) {
        // session_key 已经失效，需要重新执行登录流程
        console.log('session_key 已经失效，需要重新执行登录流程：' )
        wx.login({
          success: res => {
            data['code'] = res.code;
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            var calkdata = app.netWorkRequest(that, data, url, 'phoneNumber')
          }
        })
      }
    })
  },
  updatePhone: function(data) {
    var that = this;
    phoneNumber = data;
    var t = that.data.userCardInfo;
    t['Phone'] = data;
    this.setData({
      userCardInfo: t,
    })
  },

  // 提交更新
  sendCreateCard: function(e) {
    var that = this;
    var dt = e.detail.value;
    var t = that.data.userCardInfo;
    console.log('form发生了submit事件，携带数据为：', dt)
    if (!dt['Realname'] || dt['Realname'] == '') return app.promptModal('姓名不能为空');
    if (!t['Phone'] || t['Phone'] == '') return app.promptModal('手机号码不能为空');
    if (!app.testPhone(t['Phone'])) return app.promptModal('手机号码不合法');
    var data = dt;
    // if (t['Province'] == undefined || t['Province'] == '' || !t['Province']) //只计算到省
    //   return app.promptModal('地址不能为空');
    // data['Province'] = t['Province'];
    // data['City'] = t['City'];
    // data['County'] = t['County'];
    data['Phone'] = t['Phone'];
    if (t['Card_portrait'])
    data['Card_portrait'] = t['Card_portrait'];
    if(t['Card_address'])
    data['Card_address'] = t['Card_address'];
    //data.splice('address', 1)
    console.log('省：' + data['Province'] + '市：' + data['City'], '县：' + data['County'])
    var url = 'We_Businesscard/getAddUserCardInfo'
    var calkdata = app.netWorkRequest(that, data, url, 'perfectInfo')
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('页面加载', options)
    var avatar = options.avatar
    if (avatar && avatar != '' && avatar != undefined && avatar != 'undefined') {
      
      app.uploadImage(this, avatar);
    }
    this.getUserCardInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.getRegionList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log('页面显示')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.onShow();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})